package net.asciiworks.filesyncr.view.contentPane {
    import net.asciiworks.filesyncr.ApplicationFacade;
    import net.asciiworks.filesyncr.model.DataProxy;
    import net.asciiworks.filesyncr.model.VolumeProxy;
    
    import mx.collections.ArrayCollection;
    import mx.events.ListEvent;
    
    import org.puremvc.as3.interfaces.IMediator;
    import org.puremvc.as3.interfaces.INotification;
    import org.puremvc.as3.patterns.mediator.Mediator;
    
    import spark.events.IndexChangeEvent;

    public class DirectorySelectionMediator extends Mediator implements IMediator {
        public static const NAME:String = "DirectorySelectionMediator";

        private var volumeProxy:VolumeProxy;

        private var dataProxy:DataProxy;

        public function DirectorySelectionMediator(viewComponent:DirectorySelection) {
            super(NAME, viewComponent);
        }

        override public function onRegister():void {
            volumeProxy = facade.retrieveProxy(VolumeProxy.NAME) as VolumeProxy;
            dataProxy = facade.retrieveProxy(DataProxy.NAME) as DataProxy;

            var volumes:ArrayCollection = volumeProxy.volumes;
            directorySelection.volumes.dataProvider = volumes;

			directorySelection.source.addEventListener(ListEvent.CHANGE, source_changeHandler);
			directorySelection.volumes.addEventListener(IndexChangeEvent.CHANGE, volumes_indexChangeHandler);
			directorySelection.destination.addEventListener(ListEvent.CHANGE, destination_changeHandler);
        }

		private function source_changeHandler(event:ListEvent):void {
			dataProxy.source = event.currentTarget.selectedPath;
		}
		
		private function destination_changeHandler(event:ListEvent):void {
			dataProxy.destination = event.currentTarget.selectedPath;
		}
		
		private function volumes_indexChangeHandler(event:IndexChangeEvent):void {
			dataProxy.destinationVolume = event.currentTarget.selectedItem.name as String;
		}
		
        override public function listNotificationInterests():Array {
            return [ ApplicationFacade.VOLUMES_CHANGED ];
        }

        override public function handleNotification(note:INotification):void {
            switch (note.getName()) {
                case ApplicationFacade.VOLUMES_CHANGED:
                    var volumes:ArrayCollection = note.getBody() as ArrayCollection;
                    directorySelection.volumes.dataProvider = volumes;
                    break;
            }
        }

        private function get directorySelection():DirectorySelection {
            return viewComponent as DirectorySelection;
        }
    }
}